package com.cgx.tablet.beeper.activity;

import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.ListViewAutoScrollHelper;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;

import com.cgx.tablet.beeper.R;
import com.cgx.tablet.beeper.adapter.BizWaitAdapter;
import com.cgx.tablet.beeper.adapter.MainButtonAdapter;
import com.cgx.tablet.beeper.base.BaseActivity;
import com.cgx.tablet.beeper.bean.BizWaitBean;
import com.cgx.tablet.beeper.bean.CallBean;
import com.cgx.tablet.beeper.bean.MainButtonBean;
import com.cgx.tablet.beeper.databinding.ActivityMainBinding;
import com.cgx.tablet.beeper.event.FinishActivityEvent;
import com.cgx.tablet.beeper.event.RemoveCallbackEvent;
import com.cgx.tablet.beeper.event.TicketTransEvent;
import com.cgx.tablet.beeper.fragment.TicketNoTransferFragment;
import com.cgx.tablet.beeper.interfaces.GetCallBeanListener;
import com.cgx.tablet.beeper.interfaces.OnItemClickListener;
import com.cgx.tablet.beeper.presenter.BusinessPresenter;
import com.cgx.tablet.beeper.presenter.ChangeStatePresenter;
import com.cgx.tablet.beeper.task.TimeTaskScroll;
import com.cgx.tablet.beeper.utils.DateUtil;
import com.cgx.tablet.beeper.utils.SharedPreferenceUtil;
import com.cgx.tablet.beeper.utils.ToastUtil;
import com.cgx.tablet.beeper.view.IBusinessView;
import com.cgx.tablet.beeper.view.IChangeStateView;
import com.cgx.tablet.beeper.window.AbandonCallWindow;
import com.cgx.tablet.beeper.window.SpecifiedCallWindow;
import com.yatoooon.screenadaptation.ScreenAdapterTools;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends BaseActivity implements IBusinessView, IChangeStateView, GetCallBeanListener, OnItemClickListener, View.OnTouchListener, AbsListView.OnScrollListener{

    private ActivityMainBinding mBinding;
    private boolean isExit = false;     //是否物理返回键退出
    private boolean clickExit = false;  //是否点击了退出
    private Handler mHandler = new Handler();
    private int time = 0;       //计时
    private int buttonState;    //暂停在线的按钮状态
    private CallBean callBean;
    private BusinessPresenter businessPresenter;
    private ChangeStatePresenter changeStatePresenter;
    private BizWaitAdapter bizWaitAdapter;
    private List<BizWaitBean> bizWaitBeans = new ArrayList<>();
    private TimeTaskScroll timeTaskScroll;
    private AbandonCallWindow abandonCallWindow;
    private SpecifiedCallWindow specifiedCallWindow;
    private MainButtonAdapter mainButtonAdapter;
    public Timer timer = new Timer();
    private boolean mActionDown = false;
    private long curAutoCallTime = 0, totalAutoCallTime = 10000;   //记载当前叫号时间，弹出窗口消失后重新  2.自动叫号剩余时间默认10秒

    private List<MainButtonBean> mainButtonBeans = new ArrayList<>();
    private final int[] buttonIvs = {R.mipmap.tab_call, R.mipmap.tab_discarded_recall, R.mipmap.tab_specified_call, R.mipmap.tab_start_deal,
            R.mipmap.tab_ticket_no_transfer, R.mipmap.tab_chase_call, R.mipmap.tab_discarded, R.mipmap.tab_complete, R.mipmap.tab_help};
    private final int[] buttonTvs = {R.string.tab_call, R.string.tab_abandon_call, R.string.tab_specified_call, R.string.tab_start_deal,
            R.string.tab_ticket_no_transfer, R.string.tab_recall, R.string.tab_abandon, R.string.tab_finish, R.string.tab_help};

    private ListViewAutoScrollHelper mScrollHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        ScreenAdapterTools.getInstance().reset(this);
        ScreenAdapterTools.getInstance().loadView(getWindow().getDecorView());
        mBinding.setMainActivity(this);
        registerEventBus();
        initStatusBar(android.R.color.transparent);
        buttonState = 0;
        mBinding.userName.setText(SharedPreferenceUtil.getAccount(this));
        mBinding.window.setText(getIntent().getStringExtra("winName"));
        businessPresenter = new BusinessPresenter(this);
        changeStatePresenter = new ChangeStatePresenter(this);
        mBinding.timing.setText(DateUtil.getTime(this, time));

        mainButtonAdapter = new MainButtonAdapter(this, mainButtonBeans);
        mainButtonAdapter.setOnItemClickListener(this);
        mBinding.mainRv.setLayoutManager(new StaggeredGridLayoutManager(4, StaggeredGridLayoutManager.VERTICAL));
        mBinding.mainRv.setAdapter(mainButtonAdapter);
        setList(0, 1, 2, 8);

        initSpinner();
        initAdapter();
        businessPresenter.refreshBiz();
    }

    public void setList(int... index) {
        mainButtonBeans.clear();
        for (int i = 0; i < index.length; i++) {
            for (int j = i; j < buttonIvs.length; j++) {
                if (index[i] == j) {
                    MainButtonBean mainButtonBean = new MainButtonBean();
                    mainButtonBean.setButtonIv(buttonIvs[j]);
                    mainButtonBean.setButtonTv(buttonTvs[j]);
                    mainButtonBeans.add(mainButtonBean);
                }
            }
        }
        mainButtonAdapter.notifyDataSetChanged();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if (clickExit)
            mBinding.stateCheckSpinner.setSelection(0);
    }

    private void startAutoScroll(){
        mBinding.bizWaitLv.post(new Runnable() {
            @Override
            public void run() {
                forceScroll();
            }
        });
    }

    private void forceScroll(){
        MotionEvent event = MotionEvent.obtain(System.currentTimeMillis(), System.currentTimeMillis(), MotionEvent.ACTION_MOVE, mBinding.bizWaitLv.getWidth()/2, -1, 0);
        mScrollHelper.onTouch(mBinding.bizWaitLv, event);
    }

    public void initSpinner() {
        //TODO Spinner需要优化
        ArrayAdapter<String> payTypeAdapter = new ArrayAdapter<>(this, R.layout.item_state_spinner, getResources().getStringArray(R.array.state_type));
        payTypeAdapter.setDropDownViewResource(R.layout.item_spinner_drop);
        mBinding.stateCheckSpinner.setDropDownVerticalOffset(mBinding.stateCheckSpinner.getMeasuredHeight());
        mBinding.stateCheckSpinner.setAdapter(payTypeAdapter);
        mBinding.stateCheckSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
                if (position == 0) {
                    clickExit = false;
                    mBinding.stateIv.setImageResource(R.mipmap.ic_online);
                    changeStatePresenter.online();
                } else if (position == 1) {
                    clickExit = false;
                    mBinding.stateIv.setImageResource(R.mipmap.ic_offline);
                    changeStatePresenter.stop();
                    mHandler.removeCallbacks(automaticCallRunnable);
                } else if (position == 2) {
                    mBinding.stateIv.setImageResource(R.mipmap.ic_offline);
                    changeStatePresenter.logout();
                } else if (position == 3) {
                    clickExit = true;
                    mBinding.stateIv.setImageResource(R.mipmap.ic_offline);
                    removeAllCallback();
                    EventBus.getDefault().post(new FinishActivityEvent(FinishActivityEvent.TAG_EXITLOGIN));
                    finish();
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
                Log.e("AAA", "1111");
            }
        });
        ViewTreeObserver payTypeVto = mBinding.stateCheckSpinner.getViewTreeObserver();
        payTypeVto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                mBinding.stateCheckSpinner.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                mBinding.stateCheckSpinner.setDropDownVerticalOffset(mBinding.stateCheckSpinner.getHeight());
            }
        });
    }


    private void initAdapter() {
        mScrollHelper = new ListViewAutoScrollHelper(mBinding.bizWaitLv){
            @Override
            public void scrollTargetBy(int deltaX, int deltaY) {
                mBinding.bizWaitLv.smoothScrollBy(2, 0);
            }
        };
        mBinding.bizWaitLv.setOnTouchListener(this);
        mBinding.bizWaitLv.setOnScrollListener(this);
        bizWaitAdapter = new BizWaitAdapter(this, bizWaitBeans);
        mBinding.bizWaitLv.setAdapter(bizWaitAdapter);
        timeTaskScroll = new TimeTaskScroll(this, mBinding.bizWaitLv);
        timer.schedule(timeTaskScroll, 10, 100);
    }

    private void initCallBean(CallBean callBean) {
        mBinding.currentTicketNo.setText(callBean == null ? "" : callBean.getTicket());
        mBinding.ticketNoInfo.setText(callBean == null ? "" : getResources().getString(R.string.ticket_no_info_content, callBean.getTicket(), callBean.getBizName(), callBean.getTypeName()));
        mBinding.otherInfo.setText(callBean == null ? "" : callBean.getOtherInfo());
    }

    //呼叫
    public void call(View view) {
        mHandler.removeCallbacks(automaticCallRunnable);
        businessPresenter.call();
    }

    //弃号重呼
    public void abandonCall(View view) {
        if (curAutoCallTime != 0)
            totalAutoCallTime = totalAutoCallTime - (DateUtil.getDisTime(curAutoCallTime));      //获取时间差
        mHandler.removeCallbacks(automaticCallRunnable);
        abandonCallWindow = new AbandonCallWindow(this);
        abandonCallWindow.setGetCallBeanListener(this);
        abandonCallWindow.showAtLocation(findViewById(android.R.id.content), Gravity.BOTTOM, 0, 0);
        abandonCallWindow.setOnDismissListener(new AbandonCallWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                if (mBinding.automaticCallCb.isChecked()) {          //自动呼叫，调用呼叫接口(自动点击呼叫按钮)
                    if (totalAutoCallTime < 10000) {
                        curAutoCallTime = System.currentTimeMillis();
                        mHandler.postDelayed(automaticCallRunnable, totalAutoCallTime < 0 ? 0 : totalAutoCallTime);
                    }
                }
            }
        });
    }

    //特定呼叫
    public void specifiedCall(View view) {
        if (curAutoCallTime != 0)
            totalAutoCallTime = totalAutoCallTime - (DateUtil.getDisTime(curAutoCallTime));
        mHandler.removeCallbacks(automaticCallRunnable);
        specifiedCallWindow = new SpecifiedCallWindow(this);
        specifiedCallWindow.setGetCallBeanListener(this);
        specifiedCallWindow.showAtLocation(findViewById(android.R.id.content), Gravity.BOTTOM, 0, 0);
        specifiedCallWindow.setOnDismissListener(new SpecifiedCallWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                if (mBinding.automaticCallCb.isChecked()) {          //自动呼叫，调用呼叫接口(自动点击呼叫按钮)
                    if (totalAutoCallTime < 10000) {             //判断是否存在时间差，自动呼叫倒计时中打开窗口会有差值
                        curAutoCallTime = System.currentTimeMillis();
                        mHandler.postDelayed(automaticCallRunnable, totalAutoCallTime < 0 ? 0 : totalAutoCallTime);
                    }
                }
            }
        });
    }

    //开始办理
    public void startDeal(View view) {
        businessPresenter.deal(callBean.getTid());
    }

    //票号转移
    public void ticketNoTransfer(View view) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        TicketNoTransferFragment ticketNoTransferFragment = TicketNoTransferFragment.newInstance(callBean);
        ticketNoTransferFragment.show(fragmentManager, "ticket_transfer_dialog");
    }

    //追呼
    public void recall(View view) {
        businessPresenter.recall(callBean.getTid());
    }

    //弃号
    public void abandon(View view) {
        businessPresenter.abandon(callBean.getTid());
    }

    //完成
    public void finish(View view) {
        businessPresenter.finish(callBean.getTid());
    }

    //求助
    public void help(View view) {
        businessPresenter.help();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (isExit) {
                EventBus.getDefault().post(new FinishActivityEvent(FinishActivityEvent.TAG_EXITLOGIN));
                removeAllCallback();
                return super.onKeyDown(keyCode, event);
            } else {
                ToastUtil.showShort(this, R.string.press_again_exit);
                isExit = true;

                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        isExit = false;
                    }
                }, 2000);
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 倒计时
     */
    Runnable timeRunnable = new Runnable() {
        @Override
        public void run() {
            time++;
            mBinding.timing.setText(DateUtil.getTime(MainActivity.this, time));
            mHandler.postDelayed(timeRunnable, 1000);
        }
    };

    /**
     * 刷新
     */
    Runnable refreshRunnable = new Runnable() {
        @Override
        public void run() {
            businessPresenter.refreshBiz();
        }
    };

    /**
     * 自动呼叫
     */
    Runnable automaticCallRunnable = new Runnable() {
        @Override
        public void run() {
            if (mBinding.automaticCallCb.isChecked()) {
                businessPresenter.call();
            }
        }
    };

    @Override
    public void onOnlineSuccess() {
        if (buttonState == 0) {
            finishView();
        } else if (buttonState == 1) {
            callView(callBean);
        } else if (buttonState == 2) {
            dealView();
        }
    }

    @Override
    public void onOnlineFail(String code, String msg) {
        ToastUtil.showShort(this, msg);
    }

    @Override
    public void onStopSuccess() {
        ToastUtil.showShort(this, R.string.stop_success);
        setList();
    }

    @Override
    public void onStopFail(String code, String msg) {
        ToastUtil.showShort(this, msg);
    }

    @Override
    public void onLogoutSuccess() {
        ToastUtil.showShort(this, R.string.logout_success);
        mHandler.removeCallbacks(timeRunnable);
        mHandler.removeCallbacks(refreshRunnable);
        mHandler.removeCallbacks(automaticCallRunnable);        //移除业务操作
        finish();
        startActivity(LoginActivity.class);
    }

    @Override
    public void onLogoutFail(String code, String msg) {
        ToastUtil.showShort(this, msg);
    }

    @Override
    public void onCallSuccess(CallBean callBean) {
        curAutoCallTime = 0;    //重置当前自动呼叫开始时间为0
        totalAutoCallTime = 10000;  //重置自动叫号剩余时间默认10秒
        ToastUtil.showShort(this, R.string.call_success);
        callView(callBean);
        mHandler.postDelayed(timeRunnable, 1000);
    }

    @Override
    public void onCallFail(String code, String msg) {
        curAutoCallTime = 0;
        totalAutoCallTime = 10000;
        ToastUtil.showShort(this, msg);
    }

    @Override
    public void onRecallSuccess() {
        ToastUtil.showShort(this, R.string.recall_success);
    }

    @Override
    public void onRecallFail(String code, String msg) {
        ToastUtil.showShort(this, msg);
    }

    @Override
    public void onDealSuccess() {
        ToastUtil.showShort(this, R.string.tab_start_deal);
        dealView();
    }

    @Override
    public void onDealFail(String code, String msg) {
        ToastUtil.showShort(this, msg);
    }

    @Override
    public void onFinishSuccess() {
        finishView();
        automaticCall();
    }

    @Override
    public void onFinishFail(String code, String msg) {
        ToastUtil.showShort(this, msg);
    }

    @Override
    public void onAbandonSuccess() {
        finishView();
        automaticCall();
    }

    @Override
    public void onAbandonFail(String code, String msg) {
        ToastUtil.showShort(this, msg);
    }

    @Override
    public void onRefreshBizSuccess(List<BizWaitBean> bizWaitBeans) {
        this.bizWaitBeans.clear();
        this.bizWaitBeans.addAll(bizWaitBeans);
//        bizWaitAdapter.clear();
//        bizWaitAdapter.addCollection(bizWaitBeans);
        bizWaitAdapter.notifyDataSetChanged();
        mHandler.postDelayed(refreshRunnable, 5000);
    }

    @Override
    public void onRefreshBizFail(String code, String msg) {
        ToastUtil.showShort(this, msg);
    }

    @Override
    public void onHelpSuccess() {
        ToastUtil.showShort(this, R.string.help_success);
    }

    @Override
    public void onHelpFail(String code, String msg) {
        ToastUtil.showShort(this, msg);
    }

    //特定呼叫和弃号重呼成功
    @Override
    public void getCallBean(CallBean callBean) {
        curAutoCallTime = 0;
        totalAutoCallTime = 10000;
        callView(callBean);
        mHandler.postDelayed(timeRunnable, 1000);
    }

    //转移
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(TicketTransEvent ticketTransEvent) {
        finishView();
        automaticCall();
    }

    //移除自动呼叫Runnable
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(RemoveCallbackEvent removeCallbackEvent) {
        mHandler.removeCallbacks(automaticCallRunnable);
    }

    private void callView(CallBean callBean) {
        buttonState = 1;
        this.callBean = callBean;
        initCallBean(this.callBean);
        setList(3, 5, 6, 8);
    }

    private void dealView() {
        buttonState = 2;
        setList(4, 5, 6, 7, 8);
    }

    private void finishView() {
        buttonState = 0;
        callBean = null;
        initCallBean(null);
        setList(0, 1, 2, 8);
    }

    private void automaticCall() {
        mHandler.removeCallbacks(timeRunnable);
        time = 0;
        mBinding.timing.setText(DateUtil.getTime(this, time));
        if (mBinding.automaticCallCb.isChecked()) {          //自动呼叫，调用呼叫接口(自动点击呼叫按钮)
            curAutoCallTime = System.currentTimeMillis();       //自动呼叫倒计时开始时，记录当前时间
            mHandler.postDelayed(automaticCallRunnable, totalAutoCallTime);
        }
    }

    //移除所有业务操作
    private void removeAllCallback(){
        mHandler.removeCallbacks(timeRunnable);
        mHandler.removeCallbacks(refreshRunnable);
        mHandler.removeCallbacks(automaticCallRunnable);
    }

    @Override
    public void onItemClick(View view, int position) {
        switch (view.getId()) {
            case R.id.btn_ll:
                if ((int)view.getTag() == buttonIvs[0]) {
                    call(view);
                } else if ((int)view.getTag() == buttonIvs[1]) {
                    abandonCall(view);
                }else if ((int)view.getTag() == buttonIvs[2]) {
                    specifiedCall(view);
                }else if ((int)view.getTag() == buttonIvs[3]) {
                    startDeal(view);
                }else if ((int)view.getTag() == buttonIvs[4]) {
                    ticketNoTransfer(view);
                }else if ((int)view.getTag() == buttonIvs[5]) {
                    recall(view);
                }else if ((int)view.getTag() == buttonIvs[6]) {
                    abandon(view);
                }else if ((int)view.getTag() == buttonIvs[7]) {
                    finish(view);
                }else if ((int)view.getTag() == buttonIvs[8]) {
                    help(view);
                }
                break;
            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        switch (motionEvent.getAction()){
            case MotionEvent.ACTION_DOWN:
                mActionDown = true;
                timeTaskScroll.cancel();
                break;
            case MotionEvent.ACTION_UP:
                mActionDown = false;
                timeTaskScroll = new TimeTaskScroll(this, mBinding.bizWaitLv);
                timer.schedule(timeTaskScroll, 10, 100);
                break;
        }
        return onTouchEvent(motionEvent);
    }

    @Override
    public void onScrollStateChanged(AbsListView absListView, int scrollState) {
        switch (scrollState){
            case SCROLL_STATE_IDLE:
                if (!mActionDown)
                    forceScroll();
                break;
        }
    }

    @Override
    public void onScroll(AbsListView absListView, int i, int i1, int i2) {

    }
}
